package da_go_clickhouse_client

import (
    "fmt"
    "time"

    "gitee.com/d_alchemia/da-go-clickhouse-client/chc"
)

type User struct {
    ID         string    `orm:"column(id);type(UUID);pk"`
    Name       string    `orm:"column(name)"`
    CreateTime time.Time `orm:"column(create_time);type(Date)"`
}

func main() {

    // 配置连接信息
    // Host：            主连接地址
    // AltHosts：        集群备用连接地址，结合Host，创建所有实例连接
    // User：            用户名，Clickhouse默认用户名default
    // Pass：            密码
    // Database：        连接数据库，Clickhouse默认数据库default
    // RTO：             查询超时，单位秒
    // WTO：             写入超时，单位秒
    // DefaultTimeLoc：  时区设置，用于时间日期转换标记
    // IsCluster：       Clickhouse是否为集群标记
    config := &chc.Config{
        Host:           "10.6.2.200:9000",
        AltHosts:       "10.6.2.201:9000,10.6.2.202:9000",
        User:           "default",
        Pass:           "",
        Database:       "default",
        RTO:            10,
        WTO:            20,
        DefaultTimeLoc: time.Local,
        IsCluster:      true,
    }

    // 创建数据库连接
    if err := chc.RegisterDataBase(config); nil != err {
        _ = fmt.Errorf(err.Error())
        panic(err)
    }

    // 注册模型对象
    chc.RegisterModel(new(User))

    // 插入数据
    userC := &User{ID: "uid", Name: "Sophy", CreateTime: time.Now()}
    if err := chc.Insert(userC); nil != err {
        fmt.Println(err.Error())
    }

	// 修改数据
	userU := &User{ID: "uid", Name: "Tom", CreateTime: time.Now()}
	if num, err := chc.Update(userU); nil != err {
		fmt.Println(err.Error())
	} else {
		fmt.Printf("Been Updated %d \n", num)
	}

	// 查询数据
	userR := &User{ID: "uid"}
	if err := chc.Read(userR); nil != err {
		fmt.Println(err.Error())
	}

    // 删除数据
    userD := &User{ID: "uid"}
    if num, err := chc.Delete(userD, "id"); nil != err {
    	fmt.Println(err.Error())
	} else {
		fmt.Printf("Been deleted %d \n", num)
	}

    // var vals []*Ctest
    //
    // vals = append(vals, &TBL{ID: "a", Name: "n1", CreateDate: time.Now()})
    // vals = append(vals, &TBL{ID: "b", Name: "n2", CreateDate: time.Now()})
    // vals = append(vals, &TBL{ID: "c", Name: "n3", CreateDate: time.Now()})
    // vals = append(vals, &TBL{ID: "d", Name: "n4", CreateDate: time.Now()})

    // count, _ := chc.QueryTable("ctest").All(&vals)

    // count, _ := chc.ReadBatch(new(Ctest), &vals)

    var res []map[string]interface{}
    count, _ := chc.Raw("SELECT * FROM ctest_all").RowsToMaps(&res, "id", "name", "remark")

    rawSql := " CREATE TABLE yyyy (id UUID, org String, create_time DateTime)"
    rawSql += " ENGINE = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/db_new.yyyy', '{replica}')"
    rawSql += " PARTITION BY toYYYYMM(create_time)"
    rawSql += " ORDER BY (create_time, id)"

    if err := chc.Raw(rawSql).ExecAll(); nil != err {
        fmt.Println(err.Error())
    }

    fmt.Println(count)
}
